<!-- 防刷功能 -->
<template>
  <SearchTable ref="SearchTableRef" :query="data.query" :list="data.list" :total="data.total" @changeSize="changeSize" @changePage="changePage" @search="getSearchList" 
    @reset="resetDetails(true)" :showSet="false" @changeTh="data.dialogVisible = true">
    <template #other>
      <el-tabs v-model="data.nameType" type="card" class="demo-tabs" @tab-click="handleClick">
        <el-tab-pane label="配置列表" :name="1" />
        <el-tab-pane label="记录统计" :name="2" />
      </el-tabs>
    </template>
    <template #form>
      <Operator ref="OperatorRef" @query="queryItem" />
      <GameItem ref="GameItemRef" @query="queryGame"  v-if="!data.nameTypeShow"/>
      <el-form-item label="" v-show="!data.nameTypeShow">
        <el-select class="selectWidth120" v-model="data.query.search_type" placeholder="请选择">
          <el-option v-for="item in data.conditionList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <el-input class="width200" v-model="data.query.search_value" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="控制日期：" v-show="!data.nameTypeShow">
        <el-date-picker v-model="data.query.date" type="daterange" range-separator="-" start-placeholder="请选择开始时间"
          end-placeholder="请选择结束时间" value-format="YYYY-MM-DD" clearable :disabled-date="indexStore.disabledDateTime"/>
      </el-form-item>
    </template>
    <template #button>
      <el-button type="danger" v-permiss="'/system/destroyManager'" size="small" v-show="data.nameTypeShow" @click="data.isShowCommercial = true">
        功能开关批量控制
      </el-button>
    </template>
    <template #table>
      <template v-for="(item, index) in data.nameTypeShow?data.fields:data.fieldsBrush" :key="index">
        <el-table-column :prop="item.prop" :label="item.label" :width="item.width">
          <template #header>
            <el-tooltip v-if="item.tips" effect="dark" placement="top">
              <template #content>
                {{ item.tips }}
              </template>
              <el-icon class="ques-tips">
                <QuestionFilled />
              </el-icon>
            </el-tooltip>
            {{ item.label }}
          </template>
          <template v-if="item.prop == 'radio'" #default="scope">
            {{ scope.row.radio }}%
          </template>
          <template v-if="item.prop == 'status'" #default="scope">
            <el-tag :type="scope.row.status== 1 ? 'success' : 'danger'">{{ scope.row.status==1 ? '开启' : '关闭' }}</el-tag>
          </template>
          <template v-if="item.prop == 'operated_id'" #default="scope">
            {{ selectToLabel(indexStore.operatorArray,scope.row.operated_id) }}
          </template>
          <template v-if="item.prop == 'agent_id'" #default="scope">
            {{ selectToLabel(indexStore.agentArray,scope.row.agent_id) }}
          </template>
          <template v-if="item.prop == 'account_id'" #default="scope">
            <span class="item_check" @click="checkUser(scope.row.account_id, 1)">
              {{ scope.row.account_id }}
            </span>
          </template>
          <template v-if="item.prop == 'account'" #default="scope">
            <span class="item_details" @click="checkUser(scope.row.account, 3), data.formParams = scope.row">
              {{ scope.row.account }}
            </span>
          </template>
          <template v-if="item.prop == 'game_id'" #default="scope">
            <GameHeaderInfo :game_id="scope.row.game_id"/>
          </template>
          <template v-if="item.prop == 'before_rtp'" #default="scope">
            {{ BigHundred(scope.row.before_rtp) }}%
          </template>
          <template v-if="item.prop == 'bush_type'" #default="scope">
            <el-tag :type="scope.row.bush_type== 1 ? 'success' : 'danger'">{{ scope.row.bush_type==1 ? '已解除' : '生效中' }}</el-tag>
          </template>
          <template v-if="item.prop == 'control_start_time'" #default="scope">
            {{ setTimestampTime(scope.row.control_start_time) }}
          </template>
          <template v-if="item.prop == 'control_end_time'" #default="scope">
            {{ setTimestampTime(scope.row.control_end_time) }}
          </template>
        </el-table-column>
      </template>
      <el-table-column fixed="right" label="操作" width="90" align="center" v-if="data.nameTypeShow">
        <template #header>
          <el-tooltip effect="dark" content="点击按钮进行编辑参数" placement="top">
            <el-icon class="ques-tips">
              <QuestionFilled />
            </el-icon>
          </el-tooltip>
          编辑
        </template>
        <template #default="scope">
          <el-button type="warning" v-permiss="'/system/destroyManager'" size="small" @click="checkDetails(scope.row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </template>
  </SearchTable>

  <!-- 变更表头弹框 -->
  <tableHeader :dialogVisible="data.dialogVisible" :list="data.nameTypeShow?data.fields:data.fieldsBrush" @cancel="data.dialogVisible = false" @resetData="resetData"/>
  <!-- 玩家信息详情 -->
  <UserDetails :show="data.isUserDetails" @onHideDetails="onHideDetails" :checkedItem="data.formParams" />

  <!-- 功能开关控制 -->
  <el-dialog v-model="data.isShowCommercial" title="功能开关批量控制" :close-on-click-modal="false" :close-on-press-escape="false"
    width="50%" top="25vh" @close="data.isShowCommercial = false">
    <MultipleOperator ref="BatchControlRef">
      <template #footer>
        <form-item title="防刷功能状态" :pass="true" value="a_slots_bush_status">
          <el-radio-group v-model="data.commercialForm.a_slots_bush_status" size="large">
            <el-radio-button label="关闭" :value="0" />
            <el-radio-button label="开启" :value="1" />
          </el-radio-group>
        </form-item>
      </template>
    </MultipleOperator>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="data.isShowCommercial = false">取 消</el-button>
        <el-button type="primary" v-loading="indexStore.moduleLoading" @click="initialSynchronization">确 定</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 调控配置 -->
  <el-dialog v-model="data.isShowDetails" title="保护配置" :close-on-click-modal="false" :close-on-press-escape="false" :destroy-on-close="true"
    width="50%" :top="'18vh'" @close="data.isShowDetails = false" >
    <template #header>
      <p class="box-title mustPass">【{{ data.formParams.agent_id }}】{{ data.formParams.agent_name }}</p>
    </template>
    <div class="dialogMaxHeight">
      <el-form ref="ruleFormRef" :model="data.formParams" :inline="true" :rules="data.rules" :scroll-to-error="true">
        <form-item title="盈利档位统计时间(h)" value="statistical_time">
          <el-input-number v-model="data.formParams.statistical_time" :min="0" :max="99999999999999999999" :precision="1"
            placeholder="盈利档位统计时间(h)" clearable controls-position="right" />
          <span class="tipsText">(玩家进入游戏内游戏数据统计间隔时间；若此时间内无异常，清除数据重新开始)</span>
          </form-item>
        <form-item title="盈利判定上浮比例" value="radio">
          <el-input-number v-model="data.formParams.radio" :min="0" :max="100"
            :precision="0" placeholder="盈利判定上浮比例" clearable controls-position="right" />%
            <span class="tipsText">(与游戏默认设定的RTP相比的浮动范围，在此范围内不做异常处理)</span>
        </form-item>
        <form-item title="盈利档位数" value="position">
          <el-input-number v-model="data.formParams.position" :min="0" :max="99999999999999999999"
            :precision="0" placeholder="盈利档位数" clearable controls-position="right" />
            <span class="tipsText">(受系统检测期内盈利档位达到设定数，做异常处理)</span>
          </form-item>
        <form-item title="受控时间(h)" value="controlled_time">
          <el-input-number v-model="data.formParams.controlled_time" :min="0" :max="99999999999999999999" :precision="1"
            placeholder="受控时间(h)" clearable controls-position="right" />
            <span class="tipsText">(异常玩家满足设定条件后将玩家在此游戏内的RTP修改为70%，并持续此设定时间)</span>
          </form-item>
        <form-item title="功能状态" value="status">
          <el-radio-group v-model="data.formParams.status" size="large">
            <el-radio-button label="开启" :value="1" />
            <el-radio-button label="关闭" :value="0" />
          </el-radio-group>
          <span class="tipsText">(此功能的生效状态与否)</span>
        </form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="info" @click="data.isShowDetails = false">取 消</el-button>
        <el-button type="primary" v-loading="indexStore.moduleLoading" @click="editControl">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<!-- <template v-if="item.prop == 'game_id'" #default="scope">
  <GameHeaderInfo :game_id="scope.row.game_id"/>
</template> -->

<script lang="ts" setup>
import { reactive, onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Operator, { type QueryType } from '@/components/FormItem/Operator.vue'
import GameItem, { type GameType } from '@/components/FormItem/GameItem.vue'
import tableHeader from '@/components/tableHeader/tableHeader.vue'
import SearchTable from '@/components/SearchTable/SearchTable.vue'
import MultipleOperator from '@/components/FormItem/MultipleOperator.vue'
import UserDetails from '@/views/player/components/user-details.vue'
import GameHeaderInfo from '@/components/FormItem/GameHeaderInfo.vue'
import { throttle, selectToLabel, setCommaToArr } from '@/utils/index'
import { getDateDay, setTimeValue, setTimestampTime } from '@/utils/time'
import { BigDiv, BigHundred, BigTimeHundred, BigTimes } from '@/utils/math'
import { editBushStatus, getRTP, editRTP, getUserBush } from '@/api/game'

import { useStore } from '@/stores/index'
const indexStore = useStore()

const data = reactive({
  type: 1,
  query: {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    game_id: -1,
    platform: -1,
    search_type: 1,
    search_value:'',
    date:[getDateDay(0),getDateDay(0)]
  },
  list: [],
  total: 0,
  fields: [
    { label: '上级渠道', prop: 'operator_name', width: '150', visible: true, tips: '商户的上级代理' },
    { label: '商户昵称', prop: 'agent_name', width: '200', visible: true, tips: '商户的名称' },
    { label: '功能状态', prop: 'status', width: '120', visible: true, tips: '此功能的生效状态与否' },
    { label: '盈利档位统计时间(h)', prop: 'statistical_time', width: '', visible: true, tips: '玩家进入游戏内游戏数据统计间隔时间；若此时间内无异常，清除数据重新开始' },
    { label: '盈利判定上浮比例', prop: 'radio', width: '', visible: true, tips: '与游戏默认设定的RTP相比的浮动范围，在此范围内不做异常处理' },
    { label: '盈利档位数', prop: 'position', width: '', visible: true, tips: '受系统检测期内盈利档位达到设定数，做异常处理' },
    { label: '受控时间(h)', prop: 'controlled_time', width: '', visible: true, tips: '异常玩家满足设定条件后将玩家在此游戏内的RTP修改为70%，并持续此设定时间' },
  ],
  fieldsBrush: [
    { label: '上级渠道', prop: 'operated_id', width: '150', visible: true, tips: '商户的上级代理' },
    { label: '商户昵称', prop: 'agent_id', width: '180', visible: true, tips: '商户的名称' },
    { label: '平台ID', prop: 'account_id', width: '150', visible: true, tips: '玩家ID编号，唯一' },
    { label: '平台昵称', prop: 'account', width: '180', visible: true, tips: '玩家名称' },
    { label: '被控制游戏', prop: 'game_id', width: '200', visible: true, tips: '玩家被控制游戏' },
    { label: '控制状态', prop: 'bush_type', width: '120', visible: true, tips: '游戏控制状态' },
    { label: '控制RTP', prop: 'rtp', width: '120', visible: true, tips: '玩家被控制时的RTP' },
    { label: '控制前RTP', prop: 'before_rtp', width: '140', visible: true, tips: '玩家被控制前的RTP' },
    { label: '控制时间', prop: 'control_start_time', width: '', visible: true, tips: '玩家被控制时间' },
    { label: '解除时间', prop: 'control_end_time', width: '', visible: true, tips: '玩家解除时间' },
  ],
  dialogVisible: false,
  isShowDetails: false,
  isShowCommercial: false,
  isUserDetails: false,
  nameType: 1,
  nameTypeShow: true,
  commercialForm: {
    agent_ids: [],
    game_ids: [],
    a_slots_bush_status: 0,
  },
  conditionList: [
    { label: '平台ID', value: 1 },
    { label: '平台昵称', value: 3 }
  ],
  formParams: {
    status: 1,
    statistical_time: 0,
    radio: 0,
    position: 0,
    controlled_time: 0,
  } as any,
  rules: {
    rtp_num: [{ required: true, message: '请输入新手局数', trigger: 'blur' }],
    beginner: [{ required: true, message: '请输入新手救助次数', trigger: 'blur' }],
    nobeginner: [{ required: true, message: '请输入非新手救助次数', trigger: 'blur' }],
    rtp_check: [{ required: true, message: '请输入检测局数', trigger: 'blur' }],
    rtp_radio: [{ required: true, message: '请输入浮动率', trigger: 'blur' }],
  },
})

// 商户类别 + 商户
const queryItem = (item: QueryType) => {
  data.query.agent_id = item.agent_id
  data.query.operated_id = item.operated_id
}
// 游戏品牌 + 游戏
const queryGame = (item: GameType) => {
  data.query.platform = item.platform
  data.query.game_id = item.game_id
}

onMounted(async () => {
  getSearchList()
})

const getSearchList = async () => {
  indexStore.setPageLoading(true)
  let query = JSON.parse(JSON.stringify(data.query));
  query=setTimeValue(query)
  data.list = []
  data.total = 0
  let res = data.nameTypeShow? await getRTP(query): await getUserBush(query)
  res.data?.list?.forEach((item: any) => {
    if(data.nameTypeShow){
      let bush = setCommaToArr(item.a_slots_bush)
      item.status = Number(bush[0])
      item.statistical_time = BigDiv(Number(bush[1]),3600)
      item.radio = BigHundred(bush[2]) 
      item.position = Number(bush[3])
      item.controlled_time = BigDiv(Number(bush[4]),3600)
    }else{
      item.rtp = '70%'
    }
  })
  data.list = res.data.list
  data.total = res.data.total
}

// 选择游戏tab
const SearchTableRef = ref<any>()
const handleClick = async (value: any) => {
  data.list = []
  data.total = 0
  SearchTableRef.value.initTableMaxHeight()
  if(data.nameType != value.paneName){
    data.nameType = value.paneName
    data.nameTypeShow = !data.nameTypeShow
    resetDetails(false)
  }
}

// 详情
const checkDetails = async (row: any) => {
  data.formParams = JSON.parse(JSON.stringify(row))
  data.isShowDetails = true
}
// 查看玩家详情
const checkUser = (val: any, type: number) => {
  if (type == 3) {
    data.isUserDetails = true
  } else {
    data.query.search_type = type
    data.query.search_value = val
  }
  getSearchList()
}

// 修改保护配置
const editControl = throttle(async () => {
  const parameter = JSON.parse(JSON.stringify(data.formParams))
  if(!parameter.statistical_time || !parameter.radio || !parameter.position|| !parameter.controlled_time) return ElMessage.error('请完善配置信息')
  let a_slots_bush = parameter.status+','+BigTimes(parameter.statistical_time,3600)+','+BigTimeHundred(parameter.radio)+','+parameter.position+','+BigTimes(parameter.controlled_time,3600);
  parameter.a_slots_bush = a_slots_bush
  indexStore.setModuleLoading(true)
  await editRTP(parameter)
  ElMessage.success('修改成功')
  onHideDetails(true)
},5000)


// 功能开关控制
const initialSynchronization = async () => {
  const parameter = JSON.parse(JSON.stringify(data.commercialForm))
  Object.assign(parameter, BatchControlRef.value.SetBatchControl())
  let message = `是否${data.commercialForm.a_slots_bush_status? '开启' : '关闭'}控制？`;
  if(!parameter.agent_ids.length){
    return
  }
  ElMessageBox.confirm(message, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(async () => {
    indexStore.setModuleLoading(true)
    await editBushStatus(parameter)
    ElMessage.success('同步成功')
    onHideDetails(true)
  }).catch(() => {})
}

// 修改页数
const changeSize = (val: number) => {
  data.query.size = val
}
const changePage = (val: number) => {
  data.query.page = val
  getSearchList()
}

// 重置表头
const resetData = (val: any) => {
  if(data.nameTypeShow){
    data.fields = val
  }else{
    data.fieldsBrush = val
  }
}

// 重置
const BatchControlRef = ref<any>()
const onHideDetails = (show: boolean) => {
  data.dialogVisible = false
  data.isShowDetails = false
  data.isUserDetails = false
  if (data.isShowCommercial) {
    BatchControlRef.value.onHideDetails()
  }
  data.isShowCommercial = false
  if (show) {
    data.commercialForm = {
      agent_ids: [],
      game_ids: [],
      a_slots_bush_status: 0,
    }
    getSearchList()
  }
}
const OperatorRef = ref<any>()
const GameItemRef = ref<any>()
const resetDetails = (show:boolean) => {
  data.query = {
    page: 1,
    size: 50,
    agent_id: -1,
    operated_id: -1,
    game_id: -1,
    platform: -1,
    search_type: 1,
    search_value:'',
    date:[getDateDay(0),getDateDay(0)]
  }
  OperatorRef.value.onHideDetails()
  if(show && !data.nameTypeShow){
    GameItemRef.value.onHideDetails(-1)
  }
  getSearchList()
}
</script>

<style lang="scss" scoped>
.width500{
  width: 850px;
  max-height: 300px;
  overflow: auto;
}
.marginB5{
  width: 100%;
  padding-bottom: 2px;
  border-bottom: 1px solid #ededed;
}
</style>
